import sys
from model import StudentInfo


def get_read_file_object():
    """
    获取一个只读文件对象
    :return: file_object
    """
    try:
        r_object = open("StudentInfo.csv", "r", encoding="utf-8")
        return r_object
    except Exception:
        # StudentInfo.csv文件不存在则自动创建文件
        with open("StudentInfo.csv", "w", encoding="utf-8") as file_object:
            file_object.writelines(StudentInfo.get_csv_head())
        print("文件不存在,已自动创建!")
        try:
            r_object = open("StudentInfo.csv", "r", encoding="utf-8")
            return r_object
        except Exception as error:
            print(error)


def get_write_file_object():
    """
    获取一个只写文件对象
    :return: file_object
    """
    try:
        w_object = open("StudentInfo.csv", "w", encoding="utf-8")
        return w_object
    except Exception as error:
        print(error)


def print_mean():
    """
    输出控制菜单
    :return:
    """
    print("""
### 请输入序号选择操作: ###
    1   查询单个学生信息
    2   查询全部学生信息
    3   添加学生信息
    4   删除学生信息
    5   修改学生信息
    6   退出系统
    """)


def select_one_student_info(object_list, sid):
    """
    查询单个学生信息
    :param object_list:存储学生对象的列表
    :param sid: 查询学生的id
    :return: None
    """
    for i in object_list:
        if i.sid == sid:
            print(i)
            break
    else:
        print("未找到该学生!")


def select_all_student_info(object_list):
    """
    查询全部学生信息
    :param object_list: 存储学生对象的列表
    :return: None
    """
    for i in object_list:
        print(i)


def add_student_info(object_list, str_data):
    """
    添加学生信息
    :param object_list: 存储学生对象的列表
    :param str_data: 以","间隔的学生信息
    :return: None
    """
    object_list.append(StudentInfo(str_data))
    print("添加成功!")


def delete_student_info(object_list, sid):
    """
    删除学生信息
    :param object_list: 存储学生对象的列表
    :param sid: 删除学生的id
    :return: None
    """
    for i in object_list:
        if i.sid == sid:
            object_list.remove(i)
            print("删除成功!")
            break
    else:
        print("未找到该学生!")


def alter_student_info(object_list, str_data):
    """
    修改学生信息
    :param object_list: 存储学生对象的列表
    :param str_data: ","间隔的学生信息
    :return:
    """
    tmp_object = StudentInfo(str_data)
    for i in object_list:
        if i.sid == tmp_object.sid:
            object_list.remove(i)
            object_list.append(tmp_object)
            print("修改成功!")
            break
    else:
        print("未找到该学生!")


def exit_system(object_list):
    """
    退出系统,并将数据写入文件
    :param object_list: 存储学生对象的列表
    :return:
    """
    try:
        w_file_object = get_write_file_object()
        w_file_object.writelines(StudentInfo.get_csv_head())
        for i in object_list:
            str_data = i.to_csv_str()
            w_file_object.writelines(str_data)
        else:
            w_file_object.close()
            print("系统已退出!")
            sys.exit()
    except Exception as error:
        print(error)
